package classify

import (
	"errors"
	classifyDto "news_for_deepseek_interface/dto/admin/classify"
	"news_for_deepseek_interface/model"
	"strconv"
	"time"

	"gorm.io/gorm"
)

func Create(params classifyDto.CreateRequest) error {
	db := model.GetInstance().GetDB()

	var classify model.ClassifyModel
	if err := db.Where("title = ?", params.Title).Where("parent_id = ?", params.ParentId).First(&classify).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("分类名称已存在")
		}
	}
	if classify.Id != 0 {
		return errors.New("分类名称已存在")
	}

	//父级信息插叙
	parentPath := "0"
	if params.ParentId != 0 {

		var parentClassify model.ClassifyModel
		if err := db.Where("id = ?", params.ParentId).First(&parentClassify).Error; err != nil {
			return errors.New("父级分类不存在")
		}
		parentPath = parentClassify.ParentPath + "," + strconv.Itoa(params.ParentId)
	}

	return model.GetInstance().GetDB().Create(&model.ClassifyModel{
		Title:      params.Title,
		ParentId:   params.ParentId,
		ParentPath: parentPath,
		Type:       params.Type,
		CreatedAt:  time.Now(),
		UpdatedAt:  time.Now(),
	}).Error
}
